<template>
  <div class="page-container">
    <el-row>
      <el-col :span="24" :xs="24">
        <el-form
          :model="queryParams"
          :inline="true"
          label-position="left"
          @submit.prevent
        >
          <el-form-item :label="$t('user.username')">
            <el-input v-model="queryParams.userName" :placeholder="$t('user.usernameTip')" clearable @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item :label="$t('user.nickName')">
            <el-input v-model="queryParams.nickName" :placeholder="$t('user.nickNameTip')" clearable @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item :label="$t('status')">
            <el-select v-model="queryParams.status" :placeholder="$t('select')" clearable @keyup.enter.native="handleQuery" style="width: 140px;">
              <el-option :label="$t('enabled')" value="1" />
              <el-option :label="$t('disabled')" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('createTime')">
            <el-date-picker
              v-model="queryParams.createTime"
              type="daterange"
              clearable
              @keyup.enter.native="handleQuery"
              style="width: 240px;"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">{{$t('query')}}</el-button>
            <el-button @click="reset">{{$t('reset')}}</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>

    <div class="tool-controls">
      <el-button type="primary" plain :icon="Plus" @click="handleAdd">{{$t('add')}}</el-button>
    </div>

    <el-table v-loading="loading" :data="lists" :border="true">
      <el-table-column :label="$t('user.userNo')" align="center" prop="userId" width="140" />
      <el-table-column :label="$t('user.username')" align="center" prop="userName" />
      <el-table-column :label="$t('user.nickName')" align="center" prop="nickName" />
      <el-table-column :label="$t('user.mobile')" align="center" prop="phonenumber" width="200" />
      <el-table-column :label="$t('status')" align="center" prop="status" width="100">
        <template #default="scope">
          <el-text v-if="scope.row.status == '1'" type="success">{{$t('enabled')}}</el-text>
          <el-text v-else type="danger">{{$t('disabled')}}</el-text>
        </template>
      </el-table-column>
      <el-table-column :label="$t('createTime')" align="center" prop="createTime" width="180" :formatter="formatterTime" />
      <el-table-column :label="$t('handle')" align="center" class-name="small-padding fixed-width" width="160">
        <template #default="scope">
          <el-button
            v-if="scope.row.userId != 1"
            type="text"
            size="small"
            @click="handleEdit(scope.row)"
          >{{$t('edit')}}</el-button>
          <el-button
            v-if="scope.row.userId != 1"
            type="text"
            size="small"
            @click="handleDelete(scope.row)"
          >{{$t('delete')}}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-show="lists.length > 0"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :total="lists.length"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    ></el-pagination>
  </div>

  <!--新增修改-->
  <el-dialog :title="dialogTitle" v-model="dialogVisible" width="660px">
    <el-form ref="userForm" :model="userInfo" :rules="rules" label-width="auto">
      <el-row :span="20">
        <el-col :span="12" :xs="24">
          <el-form-item :label="$t('user.username')" prop="userName">
            <el-input v-model="userInfo.userName" :placeholder="$t('user.usernameTip')" />
          </el-form-item>
        </el-col>
        <el-col :span="12" :xs="24">
          <el-form-item :label="$t('user.password')" prop="password">
            <el-input v-model="userInfo.password" :placeholder="$t('user.passwordTip')" type="password" />
          </el-form-item> 
        </el-col>
        <el-col :span="12" :xs="24">
          <el-form-item :label="$t('user.nickName')" prop="nickName">
            <el-input v-model="userInfo.nickName" :placeholder="$t('user.nickNameTip')" />
          </el-form-item>
        </el-col>
        <el-col :span="12" :xs="24">
          <el-form-item :label="$t('user.sex')" prop="sex">
            <el-radio-group v-model="userInfo.sex">
              <el-radio label="1">{{$t('user.male')}}</el-radio>
              <el-radio label="2">{{$t('user.female')}}</el-radio>
              <el-radio label="3">{{$t('user.unknown')}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12" :xs="24">
          <el-form-item :label="$t('user.mobile')" prop="phonenumber">
            <el-input v-model="userInfo.phonenumber" :placeholder="$t('user.mobileTip')" />
          </el-form-item>
        </el-col>
        <el-col :span="12" :xs="24">
          <el-form-item :label="$t('user.email')" prop="email">
            <el-input v-model="userInfo.email" :placeholder="$t('user.emailTip')" />
          </el-form-item>
        </el-col>
        <el-col :span="12" :xs="24">
          <el-form-item :label="$t('user.belongingDepartment')" prop="deptId">
            <el-tree-select
              v-model="userInfo.deptId"
              :data="treeData"
              :render-after-expand="false"
              :check-strictly="true"
              :props="{ value: 'deptId', label: 'deptName'}"
              value-key="deptId"
              node-key="deptId"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" :xs="24">
          <el-form-item :label="$t('user.role')" prop="roles">
            <el-select
              v-model="userInfo.roles"
              :placeholder="$t('user.roleTip')"
              multiple
              collapse-tags
              collapse-tags-tooltip
            >
              <el-option
                v-for="item in roleData"
                :key="item.roleId"
                :label="item.roleName"
                :value="item.roleId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" :xs="24">
          <el-form-item :label="$t('user.post')" prop="posts">
            <el-select
              v-model="userInfo.posts"
              :placeholder="$t('user.postTip')"
              multiple
              collapse-tags
              collapse-tags-tooltip
            >
              <el-option
                v-for="item in postData"
                :key="item.postId"
                :label="item.postName"
                :value="item.postId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" :xs="24">
          <el-form-item :label="$t('status')" prop="status">
            <el-radio-group v-model="userInfo.status">
              <el-radio label="1">{{$t('enabled')}}</el-radio>
              <el-radio label="0">{{$t('disabled')}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24" :xs="24">
          <el-form-item :label="$t('user.description')" prop="description">
            <el-input type="textarea" v-model="userInfo.remark" :placeholder="$t('user.descriptionTip')" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">{{ $t('confirm') }}</el-button>
      <el-button @click="dialogVisible = false">{{ $t('cancel') }}</el-button>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from '#imports';
import { useI18n } from '#imports';
import type { FormRules } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import dayjs from 'dayjs';

const { t } = useI18n();

definePageMeta({
  title: '用户管理',
  en_title: 'User Management',
})

interface QueryParams {
  userName: string;
  nickName: string;
  status: string;
  createTime: Array<string>;
}

interface UserModel {
  userId?: string;
  deptId?: string;
  userName: string;
  nickName?: string;
  phonenumber?: string;
  status: string;
  email?: string;
  password?: string;
  sex?: string;
  remark?: string;
  posts?: number[];
  roles?: number[];
}

const sexOptions = [
  {
    label: t('user.male'),
    value: '1',
  },
  {
    label: t('user.female'),
    value: '2',
  },
  {
    label: t('user.unknown'),
    value: '3',
  },
]

const queryParams: Ref<QueryParams> = ref({
  userName: '',
  nickName: '',
  status: '',
  createTime: [],
})

const handleQuery = () => {
  currentPage.value = 1;
  getLists();
}

const reset = () => {
  queryParams.value = {
    userName: '',
    nickName: '',
    status: '',
    createTime: [],
  }
}

const dialogVisible = ref(false);
const userInfo: Ref<UserModel> = ref({
  userId: '',
  deptId: '',
  userName: '',
  nickName: '',
  phonenumber: '',
  status: '',
  email: '',
  password: '',
  sex: '1',
  remark: '',
  posts: [],
  roles: [],
});
const rules = reactive<FormRules>({
  userName: [{ required: true, message: t('user.usernameTip'), trigger: 'blur' }],
  mobile: [{ required: true, message: t('user.mobileTip'), trigger: 'blur' }],
  status: [{ required: true, message: t('select'), trigger: 'change' }],
})
const dialogTitle = ref('');
const operateType = ref('');
const handleAdd = () => {
  dialogVisible.value = true;
  operateType.value = 'add';
  dialogTitle.value = t('add');
  userInfo.value = {
    deptId: '',
    userName: '',
    nickName: '',
    phonenumber: '',
    status: '1',
    password: '',
    email: '',
    sex: '1',
    remark: '',
    posts: [],
    roles: [],
  }
}

const handleEdit = (row: UserModel) => {
  dialogVisible.value = true;
  operateType.value = 'edit';
  dialogTitle.value = t('edit');
  userInfo.value = row;
}

const submitForm = async () => {
  if (operateType.value === 'add') {
    const result: any = await userCreate(userInfo.value);
    if (result?.code === 200) {
      ElMessage.success(t('addSuccess'));
      dialogVisible.value = false;
      getLists();
    } else {
      ElMessage.error(t('fail'));
    }
  } else if (operateType.value === 'edit') {
    const result: any = await userUpdate(userInfo.value);
    if (result?.code === 200) {
      ElMessage.success(t('updateSuccess'));
      dialogVisible.value = false;
      getLists();
    } else {
      ElMessage.error(t('fail'));
    }
  }
  dialogVisible.value = false;
}

const handleDelete = (row: UserModel) => {
  ElMessageBox.confirm(t('confirmDelete'), t('prompt'), {
    confirmButtonText: t('confirm'),
    cancelButtonText: t('cancel'),
    type: 'warning',
  }).then(async () => {
    const result: any = await userDelete({ userId: row.userId });
    if (result?.code === 200) {
      ElMessage.success(t('deleteSuccess'));
      getLists();
    } else {
      ElMessage.error(t('fail'));
    }
  })
}

const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const lists: Ref = ref([]);
const getLists = async () => {
  loading.value = true;
  const params: {
    page: number;
    pageSize: number;
    userName?: string;
    nickName?: string;
    status?: string;
    startTime?: string;
    endTime?: string;
  } = {
    page: currentPage.value,
    pageSize: pageSize.value,
  }
  const { userName, nickName, status, createTime } = queryParams.value;
  userName && (params.userName = userName);
  nickName && (params.nickName = nickName);
  status && (params.status = status);
  if (createTime && createTime.length > 0) {
    params.startTime = dayjs(createTime[0]).format('YYYY-MM-DD');
    params.endTime = dayjs(createTime[1]).format('YYYY-MM-DD');
  }

  const result: any = await queryUsers(params);
  if (result?.code === 200) {
    lists.value = result.data.map((item: any) => {
      return {
        ...item,
        posts: item.posts.map((post: any) => post.postId),
        roles: item.roles.map((role: any) => role.roleId),
      }
    });
  }
  loading.value = false;
}
getLists();

const treeData: Ref = ref([]);
const getTreeData = async () => {
  const result: any = await queryAllDepts();
  if (result?.code === 200) {
    treeData.value = toTree(result.data, 'deptId', 'parentId');
  }
}
getTreeData();

const postData: Ref = ref([]);
const getPostData = async () => {
  const result: any = await queryAllPosts();
  if (result?.code === 200) {
    postData.value = result.data;
  }
}
getPostData();

const roleData: Ref = ref([]);
const getRoleData = async () => {
  const result: any = await queryAllRoles();
  if (result?.code === 200) {
    roleData.value = result.data;
  }
}
getRoleData();

const handleSizeChange = (val: number) => {
  currentPage.value = 1;
  pageSize.value = val;
  getLists();
}
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  getLists();
}

const formatterTime = (data : any) => {
  return formatDate(data.createTime, 'YYYY-MM-DD HH:mm:ss');
}
</script>